/*
 * @Author: xiehangyun 
 * @Date: 2025-05-16 10:34:07 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2025-08-15 16:31:58
 */

import Taro from "@tarojs/taro";
import { configure, makeAutoObservable } from "mobx";
import myCouponsApi from './MyCouponsApi';
import { CouponItem } from "types/type";
import dayjs from 'dayjs';
configure({ enforceActions: "never" });

class MyCouponsStore {

    constructor() {
        makeAutoObservable(this, {}, { deep: false });
    }

    page = 1;//当前页面
    pageSize = 10;//分页数
    total = 0;//总数
    list: Array<CouponItem> = [];//优惠券列表，默认显示可用的
    hasMore = true; // 是否有更多数据
    state: "未使用" | "已使用" | "已过期" = "未使用";
    error = '';//错误信息
    loading = false;//加载状态

    //获取下一页的获取优惠券
    async getNextCouponList(reset = false) {
        if (reset) {
            this.page = 1;
            this.hasMore = true;
        } else if (!this.hasMore || this.loading) {
            return;
        } else {
            this.page++;
        }
        this.loading = true;

        myCouponsApi.getCouponList({
            pageNum: this.page,
            pageSize: this.pageSize,
            state: this.state, // 已使用/未使用
            expireTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
        }).then(async res => {

            if (reset) {
                this.list = [];
                await new Promise(resolve => requestAnimationFrame(resolve));
                await new Promise(resolve => requestAnimationFrame(resolve));
                await new Promise(resolve => requestAnimationFrame(resolve));
                this.list = [...res.rows];
            } else {
                this.list = [...this.list, ...res.rows];
            }
            this.total = res.total;
            this.hasMore = (res.rows.length === this.pageSize);
            this.loading = false;
        });
    }

    setState(state: '未使用' | '已使用' | '已过期') {
        this.state = state;
        this.getNextCouponList(true); // 切换状态后返回第一页
    }

    //领取优惠券
    async receive(couponCode: string) {
        this.loading = true;
        try {
            const res = await myCouponsApi.addCouponGetRecord(couponCode);
            if (res.code === 200) {
                Taro.showToast({
                    title: '领取成功',
                    icon: 'success',
                    duration: 2000,
                })
                console.log(res);
                await this.getNextCouponList(true); // 领取成功后返回第一页
            } else {
                Taro.showToast({
                    title: res.msg,
                    icon: 'none',
                    duration: 2000,
                })
            }
        } catch (err) {
        } finally {
            this.loading = false;
        }
    }

    // 订单金额
    orderPrice: number = 0;
    setOrderPrice(orderPrice: number) {
        this.orderPrice = orderPrice;
    }

    // 删除优惠券
    del(couponGetRecordId: number) {
        myCouponsApi.del(couponGetRecordId).then(res => {
            if (res.code === 200) {
                this.list = this.list.filter(item => item.couponGetRecordId !== couponGetRecordId);
            }
        });
    }

    // 接收转赠优惠券
    receiveToken(transferToken: string) {
        myCouponsApi.receiveToken(transferToken).then(res => {
            if (res.code === 200) {
                Taro.showToast({
                    title: '接收成功',
                    icon: 'success',
                    duration: 2000,
                });
                this.getNextCouponList(true);
            } else {
                Taro.showToast({
                    title: res.msg,
                    icon: 'none',
                    duration: 2000,
                })
            }
        });
    }

    // 取消转赠
    cancelTransfer(couponGetRecordId: number) {
        myCouponsApi.cancelTransfer(couponGetRecordId).then(res => {
            this.list = this.list.map(item => {
                if (item.couponGetRecordId === couponGetRecordId) {
                    item.transferState = "已取消";
                }
                return item;
            })
        }).catch(err => {
            this.getNextCouponList(true);
        })


    }


}

const myCouponsStore = new MyCouponsStore();

export default myCouponsStore;
